import {ScrollH} from '../../components';
import {postReadRecords} from '../../services';
import {useCallback, useState} from 'react';
import {useFocusEffect} from '@react-navigation/native';
import {BindItem} from '../../mobx/home';
import {getItem} from '../../utils';
import {HISTORY_LIST} from '../../constants';
import {observer} from 'mobx-react-lite';
import {useUserInfoStore} from '../../mobx';

const History = observer(({style, navigation}: any) => {
  const [data, setData] = useState<BindItem[]>([]);
  const {userInfo} = useUserInfoStore();

  const toRouter = () => {
    if (navigation) {
      navigation.navigate('view-history');
    }
  };

  const goDetail = (bId: number) => {
    if (navigation) {
      if (!userInfo?.Token) {
        navigation.navigate('Login');
      } else if (bId) {
        navigation.navigate('cartoon-detail', {bId});
      }
    }
  };

  // 获取列表数据
  useFocusEffect(
    useCallback(() => {
      getItem(HISTORY_LIST).then((arr: string[]) => {
        postReadRecords({
          PageIndex: 1,
          PageSize: 10,
          ArticleIdList: arr || [],
        })
          .then((res: any) => {
            if (Array.isArray(res?.Data)) {
              setData(res.Data);
            } else {
              throw new Error('');
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    }, []),
  );

  return (
    <ScrollH
      data={data}
      style={style}
      onRightPress={toRouter}
      goDetail={goDetail}
    />
  );
});

export default History;
